<template>
  <div class="products-container">
    <!-- 商品详情 -->
    <div v-if="productId" class="product-detail">
      <el-button @click="backToList" class="back-button">
        <el-icon><back /></el-icon> 返回列表
      </el-button>

      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>

      <el-empty v-else-if="!productDetail" description="商品不存在或已下架" />

      <el-row :gutter="20" v-else>
        <el-col :span="24">
          <div class="product-info">
            <h1 class="product-name">{{ productDetail.product.name }}</h1>

            <!-- 价格显示 -->
            <div class="price-container">
              <!-- 原价 -->
              <div class="original-price" :class="{ 'has-promotion': productDetail.hasPromotion }">
                原价: ¥{{ productDetail.product.price }}
              </div>

              <!-- 促销价 -->
              <div v-if="productDetail.hasPromotion && productDetail.promotion" class="promotion-price">
                <template v-if="productDetail.promotion.type === 'flash'">
                  秒杀价: <span class="highlight">¥{{ productDetail.promotionPrice }}</span>
                </template>
                <template v-else-if="productDetail.promotion.type === 'discount'">
                  促销价: <span class="highlight">¥{{ calculateFinalPriceWithDiscount() }}</span>
                </template>
                <template v-else>
                  促销价: <span class="highlight">¥{{ productDetail.promotionPrice }}</span>
                </template>
                <el-tag size="small" type="danger" class="promotion-tag">{{ getPromotionTypeText(productDetail.promotion.type) }}</el-tag>
              </div>
            </div>

            <div class="product-stock">库存: {{ productDetail.product.stock }}</div>

            <!-- 促销信息 -->
            <div v-if="productDetail.hasPromotion && productDetail.promotion"
                 class="promotion-info"
                 :class="{ 'flash-promotion': productDetail.promotion.type === 'flash' }">
              <div class="promotion-name">
                <template v-if="productDetail.promotion.type === 'flash'">
                  <span class="flash-icon">⚡</span> {{ productDetail.promotion.name }}
                </template>
                <template v-else>
                  {{ productDetail.promotion.name }}
                </template>
              </div>
              <div class="promotion-rule">
                <template v-if="productDetail.promotion.type === 'flash'">
                  秒杀价: ¥{{ productDetail.promotionPrice }}
                </template>
                <template v-else>
                  {{ getPromotionRuleText(productDetail.promotion) }}
                </template>
              </div>
              <div class="promotion-time">
                活动时间: {{ formatDateTime(productDetail.promotion.startTime) }} 至 {{ formatDateTime(productDetail.promotion.endTime) }}
              </div>
            </div>

            <!-- 满减活动提示已移除，因为上方已有绿色区域显示满减信息 -->

            <div class="product-description">{{ productDetail.product.description }}</div>

            <div class="product-actions">
              <div class="action-container">
                <el-input-number v-model="quantity" :min="1" :max="productDetail.product.stock" />
                <el-button type="danger" size="large" @click="buyNow">立即购买</el-button>
              </div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 商品列表 -->
    <div v-else class="product-list">
      <!-- 促销活动展示区域 -->
      <el-row v-if="activePromotions.length > 0" :gutter="20" class="promotion-container">
        <el-col :span="24">
          <el-card shadow="hover" class="promotion-card">
            <div class="promotion-header">
              <span class="promotion-title">进行中的促销活动</span>
            </div>
            <div class="promotion-list">
              <el-carousel :interval="4000" type="card" height="150px" indicator-position="outside">
                <el-carousel-item v-for="promotion in activePromotions" :key="promotion.id" class="promotion-item">
                  <div class="promotion-content" :class="getPromotionTypeClass(promotion.type)">
                    <div class="promotion-name">{{ promotion.name }}</div>
                    <div class="promotion-type-tag">{{ getPromotionTypeText(promotion.type) }}</div>
                    <div class="promotion-rule" v-if="getPromotionRuleText(promotion)">{{ getPromotionRuleText(promotion) }}</div>
                    <div class="promotion-rule" v-else>{{ promotion.type === 'flash' ? '秒杀活动' : '促销活动' }}</div>
                    <div class="promotion-time">
                      {{ formatDateTime(promotion.startTime) }} 至 {{ formatDateTime(promotion.endTime) }}
                    </div>
                  </div>
                </el-carousel-item>
              </el-carousel>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <div class="search-container">
            <el-card shadow="hover" class="search-card">
              <div class="search-header">
                <span class="search-title">商品搜索</span>
              </div>
              <!-- 分类导航条 -->
              <div class="category-nav-container">
                <div class="category-nav">
                  <div
                    class="category-item"
                    :class="{ active: categoryId === null }"
                    @click="categoryId = null; handleCategoryChange(null)"
                  >
                    全部分类
                  </div>
                  <div
                    v-for="item in categoryList"
                    :key="item.id"
                    class="category-item"
                    :class="{ active: categoryId === item.id }"
                    @click="categoryId = item.id; handleCategoryChange(item.id)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>

              <!-- 搜索表单 -->
              <div class="search-form-container">
                <el-form :inline="true" class="search-form">
                  <div class="search-row">
                    <el-form-item label="商品名称" class="name-item">
                      <el-input
                        v-model="keyword"
                        placeholder="请输入商品名称"
                        clearable
                        @keyup.enter="searchProducts"
                        @clear="searchProducts"
                      >
                        <template #prefix>
                          <el-icon><search /></el-icon>
                        </template>
                      </el-input>
                    </el-form-item>

                    <el-form-item label="价格区间" class="price-item">
                      <div class="price-range">
                        <el-input
                          v-model="minPrice"
                          placeholder="最低价"
                          type="number"
                          class="price-input"
                          @change="searchProducts"
                        >
                          <template #prefix>¥</template>
                        </el-input>
                        <span class="price-separator">至</span>
                        <el-input
                          v-model="maxPrice"
                          placeholder="最高价"
                          type="number"
                          class="price-input"
                          @change="searchProducts"
                        >
                          <template #prefix>¥</template>
                        </el-input>
                      </div>
                    </el-form-item>

                    <el-form-item class="button-item">
                      <el-button type="primary" @click="searchProducts" class="search-button">
                        <el-icon><search /></el-icon> 搜索
                      </el-button>
                      <el-button @click="resetSearch" class="reset-button">
                        <el-icon><refresh /></el-icon> 重置
                      </el-button>
                    </el-form-item>
                  </div>
                </el-form>
              </div>
            </el-card>
          </div>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="6" v-for="product in productList" :key="product.id">
          <el-card class="product-card" @click="viewProductDetail(product.id)">
            <div class="product-info">
              <div class="product-name">{{ product.name }}</div>
              <div class="product-category">{{ getCategoryName(product.categoryId) }}</div>
              <!-- 商品价格显示 -->
              <div class="product-price-container">
                <div v-if="productPromotions[product.id] && productPromotions[product.id].isDiscount && product.price >= 100" class="product-price-with-discount">
                  <span class="original-price">¥{{ product.price }}</span>
                  <span class="discount-price">¥{{ (product.price - 20).toFixed(2) }}</span>
                </div>
                <div v-else class="product-price">¥{{ product.price }}</div>
              </div>
              <!-- 商品卡片上的满减活动标识 -->
              <div v-if="productPromotions[product.id] && productPromotions[product.id].isDiscount && productPromotions[product.id].promotion" class="card-discount-tag">
                <el-tag size="small" type="danger" effect="dark">{{ getDiscountRuleText(productPromotions[product.id].promotion) }}</el-tag>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <div class="pagination-container">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :page-sizes="[8, 16, 24, 32]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 地址选择对话框 -->
    <el-dialog
      v-model="addressDialogVisible"
      title="确认订单信息"
      width="600px"
    >
      <div class="order-address-section">
        <div class="section-header">
          <h3>收货地址</h3>
          <el-button type="primary" link @click="goToAddressPage">
            <el-icon><plus /></el-icon> 新增地址
          </el-button>
        </div>

        <div v-if="defaultAddress" class="default-address-card">
          <div class="address-card-content">
            <div class="address-info">
              <div class="address-name-phone">
                <span class="name">{{ defaultAddress.name }}</span>
                <span class="phone">{{ defaultAddress.phone }}</span>
                <el-tag v-if="defaultAddress.isDefault === 1" size="small" type="success">默认</el-tag>
              </div>
              <div class="address-location">
                {{ defaultAddress.province }} {{ defaultAddress.city }} {{ defaultAddress.district }} {{ defaultAddress.detail }}
              </div>
            </div>
            <div class="address-select">
              <el-select v-model="selectedAddressId" placeholder="选择其他地址" @change="handleAddressChange">
                <el-option
                  v-for="address in addressList"
                  :key="address.id"
                  :label="address.name + ' ' + address.phone + ' - ' + address.province + address.city + address.district"
                  :value="address.id"
                />
              </el-select>
            </div>
          </div>
        </div>

        <el-empty v-else description="暂无收货地址" />
      </div>

      <div class="order-product-section">
        <h3>商品信息</h3>
        <div class="product-info-card">
          <div class="product-name">{{ productDetail?.product?.name }}</div>
          <div class="product-price-qty">
            <div class="price-info">
              <span v-if="productDetail?.hasPromotion" class="original-price">¥{{ productDetail?.product?.price || 0 }}</span>
              <span class="product-price">¥{{ getDisplayPrice() }}</span>
            </div>
            <span class="product-qty">x {{ quantity }}</span>
          </div>
          <div v-if="productDetail?.hasPromotion && productDetail?.promotion" class="promotion-tag-container">
            <el-tag size="small" type="danger">{{ getPromotionTypeText(productDetail.promotion.type) }}</el-tag>
          </div>
        </div>
      </div>

      <div class="order-summary">
        <div class="summary-item">
          <span>商品总额：</span>
          <span class="price">¥{{ (productDetail?.product?.price || 0) * quantity }}</span>
        </div>
        <div v-if="productDetail?.hasPromotion" class="summary-item discount">
          <span>促销优惠：</span>
          <span class="price discount-price">-¥{{ calculateDiscount() }}</span>
        </div>
        <!-- 满减优惠已包含在促销优惠中 -->
        <!-- 不再单独显示满减优惠行 -->
        <div class="summary-item">
          <span>购买数量：</span>
          <span>{{ quantity }}</span>
        </div>
        <div class="summary-item total">
          <span>应付金额：</span>
          <span class="price">¥{{ calculateFinalPrice() }}</span>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addressDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmOrder" :disabled="!selectedAddressId">提交订单</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getProducts, getProductDetail, getActivePromotions, getProductPromotion } from '@/api/user'
import { getAllCategories } from '@/api/category'
import { createOrder, payOrder } from '@/api/order'
import { getAddresses } from '@/api/user'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Search, Refresh, Plus, Discount } from '@element-plus/icons-vue'
import { formatDate } from '../../utils/date'
import type {
  Product,
  Promotion,
  ProductDetail,
  Category,
  Address
} from '@/types'

// 定义API响应接口
interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
}

const route = useRoute()
const router = useRouter()

// 商品列表数据
const productList = ref<Product[]>([])
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)
const keyword = ref('')
const categoryId = ref<number | null>(null)
const minPrice = ref('')
const maxPrice = ref('')
const categoryList = ref<Category[]>([])

// 促销活动数据
const activePromotions = ref<Promotion[]>([])

// 商品促销信息缓存
interface ProductPromotionInfo {
  hasPromotion: boolean;
  promotion?: Promotion;
  isDiscount: boolean; // 是否是满减活动
}

const productPromotions = ref<Record<number, ProductPromotionInfo>>({})

// 商品详情数据
const productId = computed(() => route.query.id ? Number(route.query.id) : null)
const productDetail = ref<ProductDetail | null>(null)
const quantity = ref(1)
const loading = ref(false)

// 获取商品列表
const getProductList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      keyword: keyword.value,
      categoryId: categoryId.value,
      minPrice: minPrice.value,
      maxPrice: maxPrice.value,
      sortField: 'price',
      sortOrder: 'asc'
    }

    console.log('获取商品列表，参数:', params)
    const response = await getProducts(params) as unknown as ApiResponse<{records: Product[], total: number}>
    console.log('获取商品列表响应:', response)

    if (response.code === 200) {
      // 直接使用原始响应
      productList.value = response.data.records
      total.value = response.data.total
      console.log('商品列表数据:', productList.value)

      // 获取每个商品的促销信息
      fetchProductPromotions()
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

// 获取商品的促销信息
const fetchProductPromotions = async () => {
  // 清空之前的缓存
  productPromotions.value = {}

  // 对每个商品获取促销信息
  for (const product of productList.value) {
    try {
      const response = await getProductPromotion(product.id) as unknown as ApiResponse<any>

      if (response.code === 200) {
        const hasPromotion = response.data.hasPromotion

        if (hasPromotion) {
          const promotion = response.data.promotion
          const isDiscount = promotion.type === 'discount'

          productPromotions.value[product.id] = {
            hasPromotion,
            promotion,
            isDiscount
          }

          console.log(`商品ID ${product.id} 有促销活动:`, promotion.type)
        } else {
          productPromotions.value[product.id] = {
            hasPromotion: false,
            isDiscount: false
          }
        }
      }
    } catch (error) {
      console.error(`获取商品ID ${product.id} 的促销信息失败:`, error)
      productPromotions.value[product.id] = {
        hasPromotion: false,
        isDiscount: false
      }
    }
  }

  console.log('商品促销信息缓存:', productPromotions.value)
}

// 获取分类列表
const fetchCategoryList = async () => {
  try {
    const response = await getAllCategories() as unknown as ApiResponse<Category[]>
    console.log('获取分类列表响应:', response)

    if (response.code === 200) {
      categoryList.value = response.data
      console.log('分类列表数据:', categoryList.value)
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

// 重置搜索条件
const resetSearch = () => {
  keyword.value = ''
  categoryId.value = null // 重置为全部分类
  minPrice.value = ''
  maxPrice.value = ''
  currentPage.value = 1
  getProductList()
}

// 获取商品详情
const fetchProductDetail = async (id: number) => {
  loading.value = true
  productDetail.value = null

  try {
    console.log('开始获取商品详情，ID:', id)
    const response = await getProductDetail(id) as unknown as ApiResponse<ProductDetail>
    console.log('获取商品详情响应:', response)

    if (response.code === 200) {
      productDetail.value = response.data
      console.log('商品详情数据:', productDetail.value)

      // 调试促销信息
      if (productDetail.value.hasPromotion) {
        console.log('商品有促销活动:', productDetail.value.promotion)
        console.log('促销类型:', productDetail.value.promotion?.type)
        console.log('促销规则:', productDetail.value.promotion?.rules)
        console.log('促销价格:', productDetail.value.promotionPrice, '类型:', typeof productDetail.value.promotionPrice)

        // 尝试解析促销规则
        if (productDetail.value.promotion?.rules) {
          try {
            console.log('尝试解析促销规则:', productDetail.value.promotion.rules)
            const rules = JSON.parse(productDetail.value.promotion.rules)
            console.log('解析后的促销规则:', rules)

            // 如果是秒杀活动，直接从规则中获取价格
            if (productDetail.value.promotion?.type === 'flash' && rules.price !== undefined) {
              console.log('从规则中获取秒杀价格:', rules.price, '类型:', typeof rules.price)

              // 强制转换为数字
              const rulePrice = Number(rules.price)
              console.log('转换后的规则价格:', rulePrice)

              if (!isNaN(rulePrice)) {
                productDetail.value.promotionPrice = rulePrice
                console.log('从规则中更新秒杀价格为:', productDetail.value.promotionPrice)
              } else {
                console.error('规则中的价格转换为数字失败')
              }
            }
          } catch (e) {
            console.error('解析促销规则失败:', e)
          }
        }

        // 如果是秒杀活动，再次检查促销价格
        if (productDetail.value.promotion?.type === 'flash') {
          console.log('检测到秒杀活动，当前价格:', productDetail.value.promotionPrice)

          // 确保价格是数字
          if (typeof productDetail.value.promotionPrice === 'string') {
            const numericPrice = Number(productDetail.value.promotionPrice)
            console.log('将字符串价格转换为数字:', numericPrice)

            if (!isNaN(numericPrice)) {
              productDetail.value.promotionPrice = numericPrice
            } else {
              console.error('价格转换为数字失败')
            }
          }

          console.log('转换后的秒杀价格:', productDetail.value.promotionPrice)

          // 再次检查秒杀价格
          await checkFlashSalePrice(id)

          // 最后检查价格是否正确设置
          console.log('最终商品详情中的促销价格:', productDetail.value.promotionPrice)
        }
      } else {
        console.log('商品没有促销活动')
      }
    } else {
      ElMessage.error('获取商品详情失败')
    }
  } catch (error) {
    console.error('获取商品详情失败:', error)
    ElMessage.error('获取商品详情失败')
  } finally {
    loading.value = false
  }
}

// 检查秒杀价格
const checkFlashSalePrice = async (productId: number) => {
  try {
    console.log('开始检查商品ID:', productId, '的秒杀价格')
    const response = await getProductPromotion(productId) as unknown as ApiResponse<any>
    console.log('获取商品促销信息响应:', response)

    if (response.code === 200 && response.data.hasPromotion) {
      const promotion = response.data.promotion
      const promotionPrice = response.data.promotionPrice

      console.log('促销活动类型:', promotion.type)
      console.log('促销活动价格:', promotionPrice)
      console.log('促销活动规则:', promotion.rules)

      // 如果是秒杀活动，更新价格
      if (promotion.type === 'flash' && productDetail.value) {
        console.log('检测到秒杀活动')

        // 确保价格是数字
        if (promotionPrice !== undefined && promotionPrice !== null) {
          console.log('从API响应中获取到秒杀价格:', promotionPrice, '类型:', typeof promotionPrice)

          // 强制转换为数字
          const numericPrice = Number(promotionPrice)
          console.log('转换后的秒杀价格:', numericPrice)

          if (!isNaN(numericPrice)) {
            productDetail.value.promotionPrice = numericPrice
            console.log('更新秒杀价格为:', productDetail.value.promotionPrice)
          } else {
            console.error('秒杀价格转换为数字失败')
          }

          // 尝试解析规则，获取秒杀价格
          if (promotion.rules) {
            try {
              console.log('尝试解析秒杀规则:', promotion.rules)
              const rules = JSON.parse(promotion.rules)
              console.log('解析后的规则:', rules)

              if (rules.price !== undefined) {
                console.log('规则中的秒杀价格:', rules.price, '类型:', typeof rules.price)

                // 强制转换为数字
                const rulePrice = Number(rules.price)
                console.log('转换后的规则价格:', rulePrice)

                if (!isNaN(rulePrice)) {
                  // 如果规则中有价格，优先使用规则中的价格
                  productDetail.value.promotionPrice = rulePrice
                  console.log('最终使用的秒杀价格:', productDetail.value.promotionPrice)
                } else {
                  console.error('规则中的价格转换为数字失败')
                }
              } else {
                console.warn('规则中没有找到price字段')
              }
            } catch (e) {
              console.error('解析秒杀规则失败:', e)
            }
          } else {
            console.warn('促销活动没有规则字段')
          }
        } else {
          console.error('秒杀价格未定义或为null')
        }

        // 最后检查价格是否正确设置
        console.log('最终商品详情中的促销价格:', productDetail.value.promotionPrice)
      }
    }
  } catch (error) {
    console.error('获取商品促销信息失败:', error)
  }
}

// 获取促销类型文本
const getPromotionTypeText = (type: string) => {
  if (!type) return '';

  const typeMap: Record<string, string> = {
    'discount': '满减',
    'percent': '折扣',
    'flash': '秒杀'
  };

  return typeMap[type] || type;
}

// 获取促销规则文本
const getPromotionRuleText = (promotion: Promotion) => {
  if (!promotion || !promotion.rules) return '';

  try {
    console.log('获取促销规则文本，规则:', promotion.rules);
    const rules = JSON.parse(promotion.rules);
    console.log('解析后的规则:', rules);
    const type = promotion.type;

    if (type === 'discount') {
      return `满${rules.condition}元减${rules.discount}元`;
    } else if (type === 'percent') {
      return `${rules.percent * 10}折`;
    } else if (type === 'flash') {
      // 确保price存在且不是undefined
      if (rules.price !== undefined) {
        return `秒杀价${rules.price}元`;
      } else {
        console.error('秒杀价格未定义:', rules);
        return '秒杀价'; // 默认不显示具体价格
      }
    }

    return '';
  } catch (e) {
    console.error('解析促销规则出错:', e, promotion.rules);
    // 添加更多日志以便调试
    console.log('促销活动原始数据:', promotion);

    // 如果是秒杀活动，默认显示99.9元
    if (promotion.type === 'flash') {
      return '秒杀价99.9元';
    }

    return '';
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  return formatDate ? formatDate(new Date(dateStr), 'yyyy-MM-dd HH:mm') : dateStr;
}

// 获取显示价格
const getDisplayPrice = (): number => {
  if (!productDetail.value) return 0;

  // 如果是满减活动，返回满减后的价格
  if (productDetail.value.hasPromotion && productDetail.value.promotion && productDetail.value.promotion.type === 'discount') {
    try {
      const price = productDetail.value.product.price;
      if (price >= 100) { // 满100减20
        const rules = JSON.parse(productDetail.value.promotion.rules);
        const discount = rules.discount || 20; // 默认减20
        return price - discount;
      }
    } catch (e) {
      console.error('计算满减价格出错:', e);
    }
  }

  // 其他类型的促销
  if (productDetail.value.hasPromotion && productDetail.value.promotionPrice !== undefined) {
    return productDetail.value.promotionPrice;
  }

  return productDetail.value.product.price;
}

// 计算折扣金额
const calculateDiscount = (): string => {
  if (!productDetail.value || !productDetail.value.hasPromotion) return '0';

  const originalPrice = productDetail.value.product.price;
  let promotionPrice;

  // 如果是满减活动，使用满减后的价格
  if (productDetail.value.promotion && productDetail.value.promotion.type === 'discount') {
    try {
      if (originalPrice >= 100) { // 满100减20
        const rules = JSON.parse(productDetail.value.promotion.rules);
        const discount = rules.discount || 20; // 默认减20
        promotionPrice = originalPrice - discount;
      } else {
        promotionPrice = originalPrice; // 不满足条件，使用原价
      }
    } catch (e) {
      console.error('计算满减折扣出错:', e);
      promotionPrice = originalPrice;
    }
  } else if (productDetail.value.promotionPrice !== undefined) {
    // 其他类型的促销
    promotionPrice = productDetail.value.promotionPrice;
  } else {
    return '0'; // 没有促销价格
  }

  const discount = (originalPrice - promotionPrice) * quantity.value;

  return discount.toFixed(2);
}

// 检查是否有满减活动
const hasDiscountPromotion = computed(() => {
  // 检查是否有满减类型的促销活动
  return activePromotions.value.some(promotion => promotion.type === 'discount');
});

// 获取满减活动信息
const getDiscountPromotion = computed(() => {
  return activePromotions.value.find(promotion => promotion.type === 'discount');
});

// 获取满减规则文本
const getDiscountRuleText = (promotion: Promotion | undefined) => {
  if (!promotion || !promotion.rules || promotion.type !== 'discount') return '';

  try {
    const rules = JSON.parse(promotion.rules);
    return `满${rules.condition}元减${rules.discount}元`;
  } catch (e) {
    console.error('解析满减规则出错:', e);
    return '满减活动';
  }
};

// 满减活动相关
const showOrderDiscount = computed(() => {
  if (!productDetail.value || !hasDiscountPromotion.value) return false;

  const totalPrice = productDetail.value.hasPromotion && productDetail.value.promotionPrice !== undefined
    ? productDetail.value.promotionPrice * quantity.value
    : productDetail.value.product.price * quantity.value;

  // 只有当有满减活动且总价满足条件时才显示满减
  return totalPrice >= 100; // 满100减20
});

const orderDiscountAmount = computed(() => {
  return showOrderDiscount.value ? 20 : 0; // 满100减20元
});

// 计算最终价格
const calculateFinalPrice = (): string => {
  if (!productDetail.value) return '0';

  let price = 0;

  // 如果是满减活动，使用满减后的价格
  if (productDetail.value.hasPromotion && productDetail.value.promotion && productDetail.value.promotion.type === 'discount') {
    try {
      const originalPrice = productDetail.value.product.price;
      if (originalPrice >= 100) { // 满100减20
        const rules = JSON.parse(productDetail.value.promotion.rules);
        const discount = rules.discount || 20; // 默认减20
        price = (originalPrice - discount) * quantity.value;
      } else {
        price = originalPrice * quantity.value;
      }
    } catch (e) {
      console.error('计算满减最终价格出错:', e);
      price = productDetail.value.product.price * quantity.value;
    }
  } else if (productDetail.value.hasPromotion && productDetail.value.promotionPrice !== undefined) {
    // 其他类型的促销
    price = productDetail.value.promotionPrice * quantity.value;
  } else {
    price = productDetail.value.product.price * quantity.value;
  }

  // 注意：我们不再单独应用满减折扣，因为已经在上面的价格计算中包含了

  return price.toFixed(2);
}

// 计算应用满减后的单件商品价格
const calculateFinalPriceWithDiscount = (): string => {
  if (!productDetail.value) return '0';

  // 获取商品价格
  let price = productDetail.value.hasPromotion && productDetail.value.promotionPrice !== undefined
    ? productDetail.value.promotionPrice
    : productDetail.value.product.price;

  // 如果是满减活动且单件商品价格已经满足满减条件，直接应用满减
  if (productDetail.value.hasPromotion &&
      productDetail.value.promotion &&
      productDetail.value.promotion.type === 'discount' &&
      price >= 100) {
    try {
      const rules = JSON.parse(productDetail.value.promotion.rules);
      const discount = rules.discount || 20; // 默认减20
      return (price - discount).toFixed(2);
    } catch (e) {
      console.error('解析满减规则出错:', e);
      return price.toFixed(2);
    }
  }

  return price.toFixed(2);
}

// 监听路由参数变化
watch(() => route.query.id, (newId) => {
  if (newId) {
    fetchProductDetail(Number(newId))
  }
})

// 获取进行中的促销活动
const fetchActivePromotions = async () => {
  try {
    const response = await getActivePromotions() as unknown as ApiResponse<Promotion[]>
    console.log('获取促销活动响应:', response)

    if (response.code === 200) {
      activePromotions.value = response.data
      console.log('获取到的促销活动:', activePromotions.value)

      // 刷新商品列表，确保价格是最新的
      if (productId.value) {
        // 如果在商品详情页，刷新商品详情
        fetchProductDetail(productId.value)
      } else {
        // 如果在商品列表页，刷新商品列表
        getProductList()
      }
    }
  } catch (error) {
    console.error('获取促销活动失败:', error)
  }
}

// 获取促销活动类型对应的样式类
const getPromotionTypeClass = (type: string): string => {
  if (!type) return '';

  const typeClassMap: Record<string, string> = {
    'discount': 'promotion-discount',
    'percent': 'promotion-percent',
    'flash': 'promotion-flash'
  };

  return typeClassMap[type] || '';
}

// 页面加载时获取数据
onMounted(() => {
  // 获取分类列表
  fetchCategoryList()

  // 获取促销活动
  fetchActivePromotions()

  if (productId.value) {
    fetchProductDetail(productId.value)
  } else {
    getProductList()
  }
})

// 查看商品详情
const viewProductDetail = (id: number): void => {
  router.push(`/user/products?id=${id}`)
}

// 返回商品列表
const backToList = (): void => {
  router.push('/user/products')
}

// 处理分类点击
const handleCategoryChange = (_categoryId: number | null): void => {
  currentPage.value = 1
  getProductList()
}

// 搜索商品
const searchProducts = (): void => {
  currentPage.value = 1
  getProductList()
}

// 处理页码变化
const handleCurrentChange = (page: number): void => {
  currentPage.value = page
  getProductList()
}

// 处理每页条数变化
const handleSizeChange = (size: number): void => {
  pageSize.value = size
  currentPage.value = 1
  getProductList()
}

// 地址列表
const addressList = ref<Address[]>([])
const selectedAddressId = ref<number | null>(null)
const addressDialogVisible = ref(false)
const defaultAddress = computed<Address | null>(() => {
  if (!addressList.value.length) return null

  // 首先查找默认地址
  const defaultAddr = addressList.value.find(addr => addr.isDefault === 1)
  if (defaultAddr) return defaultAddr

  // 如果没有默认地址，返回第一个地址
  return addressList.value[0]
})

// 获取地址列表
const fetchAddressList = async () => {
  try {
    const response = await getAddresses() as unknown as ApiResponse<Address[]>
    console.log('获取地址列表响应:', response)

    if (response.code === 200) {
      addressList.value = response.data
      console.log('地址列表数据:', addressList.value)

      if (addressList.value.length > 0) {
        // 默认选择默认地址或第一个地址
        const defaultAddr = addressList.value.find(addr => addr.isDefault === 1)
        selectedAddressId.value = defaultAddr ? defaultAddr.id : addressList.value[0].id
      }
    }
  } catch (error) {
    console.error('获取地址列表失败:', error)
    ElMessage.error('获取地址列表失败')
  }
}

// 处理地址变更
const handleAddressChange = (addressId: number): void => {
  selectedAddressId.value = addressId
}

// 跳转到地址管理页面
const goToAddressPage = (): void => {
  router.push('/user/address')
}

// 立即购买
const buyNow = async (): Promise<void> => {
  if (!productDetail.value) {
    ElMessage.warning('商品信息不存在')
    return
  }

  // 检查库存
  if (productDetail.value.stock < quantity.value) {
    ElMessage.warning('商品库存不足')
    return
  }

  // 获取地址列表
  await fetchAddressList()

  if (addressList.value.length === 0) {
    ElMessageBox.confirm('您还没有收货地址，是否前往添加？', '提示', {
      confirmButtonText: '前往添加',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      router.push('/user/address')
    }).catch(() => {})
    return
  }

  // 显示地址选择对话框
  addressDialogVisible.value = true
}

// 确认订单
const confirmOrder = async (): Promise<void> => {
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址')
    return
  }

  if (!productDetail.value) {
    ElMessage.warning('商品信息不存在')
    return
  }

  try {
    // 创建订单数据
    const orderData = {
      addressId: selectedAddressId.value,
      items: [
        {
          productId: productDetail.value.product.id,
          quantity: quantity.value
        }
      ]
    }

    // 记录满减信息，方便调试
    if (showOrderDiscount.value) {
      console.log('应用满减活动：满100减20，折扣金额：', orderDiscountAmount.value);
      console.log('满减活动应用条件：', hasDiscountPromotion.value ? '有满减活动' : '无满减活动',
                 '总价满足条件：',
                 (productDetail.value.hasPromotion && productDetail.value.promotionPrice !== undefined
                  ? productDetail.value.promotionPrice * quantity.value
                  : productDetail.value.product.price * quantity.value) >= 100);
    } else {
      console.log('不应用满减活动，原因：',
                 !hasDiscountPromotion.value ? '没有满减活动' : '总价不满足条件',
                 '当前总价：',
                 (productDetail.value.hasPromotion && productDetail.value.promotionPrice !== undefined
                  ? productDetail.value.promotionPrice * quantity.value
                  : productDetail.value.product.price * quantity.value));
    }

    // 创建订单
    const response = await createOrder(orderData) as unknown as ApiResponse<{orderNo: string}>
    console.log('创建订单响应:', response)

    if (response.code === 200) {
      const orderNo = response.data.orderNo
      ElMessage.success('订单创建成功')

      // 询问是否立即支付
      ElMessageBox.confirm('订单已创建，是否立即支付？', '提示', {
        confirmButtonText: '立即支付',
        cancelButtonText: '稍后支付',
        type: 'info'
      }).then(async () => {
        // 支付订单
        const payResponse = await payOrder(orderNo) as unknown as ApiResponse<any>
        console.log('支付订单响应:', payResponse)

        if (payResponse.code === 200) {
          ElMessage.success('支付成功')
          // 跳转到订单详情页
          router.push(`/user/orders?orderNo=${orderNo}`)
        } else {
          ElMessage.error(payResponse.message || '支付失败')
          // 跳转到订单列表页
          router.push('/user/orders')
        }
      }).catch(() => {
        // 跳转到订单列表页
        router.push('/user/orders')
      })

      // 关闭地址选择对话框
      addressDialogVisible.value = false
    } else {
      ElMessage.error(response.message || '创建订单失败')
    }
  } catch (error) {
    console.error('创建订单失败:', error)
    ElMessage.error('创建订单失败，请稍后重试')
  }
}

// 获取分类名称
const getCategoryName = (categoryId: number | null): string => {
  if (!categoryId) return '未分类'
  const category = categoryList.value.find(item => item.id === categoryId)
  return category ? category.name : '未知分类'
}
</script>

<style scoped>
.products-container {
  padding: 20px 0;
}

/* 促销活动样式 */
.promotion-container {
  margin-bottom: 20px;
}

.promotion-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
  padding: 5px 15px 15px;
  overflow: visible;
}

.promotion-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
}

.promotion-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-left: 10px;
}

.promotion-title:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #f56c6c;
  border-radius: 2px;
}

.promotion-list {
  padding: 10px 0;
}

.promotion-item {
  height: 100%;
}

.promotion-content {
  height: 100%;
  padding: 20px;
  border-radius: 8px;
  color: white;
  display: flex;
  flex-direction: column;
  justify-content: center;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
}

.promotion-content:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.promotion-content::before {
  content: '';
  position: absolute;
  top: -20px;
  right: -20px;
  width: 100px;
  height: 100px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.promotion-content::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.2);
  z-index: 1;
}

.promotion-content > * {
  position: relative;
  z-index: 2;
}

.promotion-discount {
  background: linear-gradient(135deg, #30fa37 0%, #18ee09 100%);
}

.promotion-percent {
  background: linear-gradient(135deg, #35f16a 0%, #0bf516 100%);
}

.promotion-flash {
  background: linear-gradient(135deg, #CCFF90 0%, #8BC34A 100%);
}

.promotion-name {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #ffffff;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.5);
}

.promotion-type-tag {
  position: absolute;
  top: 10px;
  right: 10px;
  background: rgba(255, 255, 255, 0.3);
  padding: 2px 8px;
  border-radius: 10px;
  font-size: 12px;
  color: #ffffff;
  font-weight: bold;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.promotion-rule {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #ffffff;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

.promotion-time {
  font-size: 12px;
  opacity: 1;
  color: #ffffff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.4);
  display: none; /* 隐藏时间信息 */
}

/* 满减活动提示样式 */
.discount-promotion-info {
  margin: 15px 0;
  padding: 10px 15px;
  background-color: #fff1f0;
  border-radius: 8px;
  border: 1px dashed #f56c6c;
  display: flex;
  align-items: center;
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0.4);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(245, 108, 108, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(245, 108, 108, 0);
  }
}

.discount-tag {
  margin-right: 10px;
}

.discount-rule {
  font-size: 16px;
  font-weight: bold;
  color: #f56c6c;
  margin-right: 15px;
}

.final-price {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
  background-color: #fff6f6;
  padding: 5px 10px;
  border-radius: 4px;
  margin-left: auto;
}

.search-container {
  margin-bottom: 20px;
}

.search-card {
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
  padding: 5px 15px 15px;
}

.search-header {
  margin-bottom: 15px;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 10px;
  display: flex;
  align-items: center;
}

.search-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  position: relative;
  padding-left: 10px;
}

.search-title:before {
  content: '';
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  width: 4px;
  height: 16px;
  background-color: #409EFF;
  border-radius: 2px;
}

/* 分类导航条样式 */
.category-nav-container {
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  position: relative;
}

.category-nav {
  display: flex;
  flex-wrap: nowrap;
  overflow-x: auto;
  white-space: nowrap;
  padding: 5px 0;
  scrollbar-width: thin;
  -ms-overflow-style: none;
}

.category-nav::-webkit-scrollbar {
  height: 4px;
}

.category-nav::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 4px;
}

.category-nav::-webkit-scrollbar-track {
  background-color: #f2f6fc;
}

.category-item {
  display: inline-block;
  padding: 8px 16px;
  margin-right: 8px;
  border-radius: 20px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #f5f7fa;
  color: #606266;
  text-align: center;
  user-select: none;
}

.category-item:hover {
  background-color: #e6f1fc;
  color: #409EFF;
}

.category-item.active {
  background-color: #409EFF;
  color: white;
  font-weight: 500;
}

.search-form-container {
  padding-top: 5px;
}

.search-form {
  width: 100%;
}

.search-row {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  margin-bottom: 10px;
}

.search-form .el-form-item {
  margin-bottom: 10px;
  margin-right: 15px;
}

.search-form .el-form-item__label {
  font-weight: 500;
  color: #606266;
}

/* 调整各个搜索项的宽度 */
.search-form .name-item {
  width: 220px;
}

.search-form .category-item {
  width: 180px;
}

.search-form .price-item {
  width: 280px;
}

.search-form .button-item {
  margin-left: auto;
  margin-right: 0;
}

.price-range {
  display: flex;
  align-items: center;
}

.price-input {
  width: 120px !important;
}

.price-separator {
  margin: 0 8px;
  color: #909399;
}

.search-button, .reset-button {
  width: 90px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.reset-button {
  margin-left: 10px;
}

.search-form .el-button .el-icon {
  margin-right: 4px;
}

/* 美化输入框和下拉框 */
.search-form .el-input__inner,
.search-form .el-select .el-input__inner {
  border-radius: 4px;
}

/* 隐藏数字输入框的加减按钮 */
.price-input input::-webkit-outer-spin-button,
.price-input input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* Firefox */
.price-input input[type=number] {
  -moz-appearance: textfield;
  appearance: textfield;
}

.product-card {
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  border: none;
}

.product-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.product-info {
  padding: 15px;
  text-align: center;
}

.product-name {
  font-size: 16px;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #303133;
}

.product-category {
  font-size: 12px;
  color: #909399;
  background-color: #f5f7fa;
  padding: 2px 8px;
  border-radius: 10px;
  display: inline-block;
  margin-bottom: 8px;
}

.product-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  display: inline-block;
  position: relative;
}

.product-price::before {
  content: '';
  position: absolute;
  left: -10px;
  right: -10px;
  bottom: -2px;
  height: 6px;
  background-color: rgba(245, 108, 108, 0.1);
  z-index: -1;
  border-radius: 3px;
}

/* 商品卡片上的满减标签 */
.card-discount-tag {
  margin-top: 8px;
  display: flex;
  justify-content: center;
}

/* 商品价格容器 */
.product-price-container {
  margin: 8px 0;
}

/* 带满减的价格显示 */
.product-price-with-discount {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.product-price-with-discount .original-price {
  text-decoration: line-through;
  color: #999;
  font-size: 14px;
}

.product-price-with-discount .discount-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 商品详情样式 */
.product-detail {
  padding: 20px;
}

/* 地址选择对话框样式 */
.order-address-section,
.order-product-section {
  margin-bottom: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.default-address-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  background-color: #f8f9fa;
}

.address-card-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.address-info {
  flex: 1;
}

.address-name-phone {
  margin-bottom: 8px;
}

.address-name-phone .name {
  font-weight: bold;
  margin-right: 10px;
}

.address-name-phone .phone {
  color: #606266;
  margin-right: 10px;
}

.address-location {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.address-select {
  width: 200px;
  margin-left: 15px;
}

.product-info-card {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  padding: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-name {
  font-size: 14px;
  color: #303133;
  flex: 1;
}

.product-price-qty {
  text-align: right;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.price-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.price-info .original-price {
  text-decoration: line-through;
  color: #999;
  font-size: 12px;
}

.product-price {
  color: #f56c6c;
  font-weight: bold;
  margin-right: 10px;
}

.product-qty {
  color: #909399;
}

.promotion-tag-container {
  margin-top: 5px;
}

.order-summary {
  background-color: #f8f8f8;
  padding: 15px;
  border-radius: 4px;
  margin-top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
}

.summary-item.discount .discount-price {
  color: #67c23a;
}

.summary-item.total {
  font-weight: bold;
  border-top: 1px solid #dcdfe6;
  padding-top: 10px;
  margin-top: 10px;
}

.price {
  color: #f56c6c;
}

.back-button {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px;
  margin-bottom: 20px;
}

.product-detail .product-info {
  padding: 0 20px;
}

.product-detail .product-name {
  font-size: 24px;
  margin-bottom: 10px;
  white-space: normal;
}

/* 价格容器 */
.price-container {
  margin-bottom: 15px;
}

.original-price {
  font-size: 16px;
  color: #666;
}

.original-price.has-promotion {
  text-decoration: line-through;
  color: #999;
}

.promotion-price {
  color: #f56c6c;
  font-size: 24px;
  font-weight: bold;
  margin-top: 5px;
}

.promotion-price .highlight {
  font-size: 28px;
}

.promotion-tag {
  margin-left: 10px;
}

/* 促销信息 */
.promotion-info {
  background-color: #A5D6A7;
  border: 1px solid #66BB6A;
  border-radius: 4px;
  padding: 10px 15px;
  margin-bottom: 15px;
  transition: all 0.3s ease;
}

.promotion-info.flash-promotion {
  background-color: #FF9800;
  border: 1px solid #F57C00;
  animation: flash-pulse 2s infinite;
}

@keyframes flash-pulse {
  0% { box-shadow: 0 0 0 0 rgba(255, 152, 0, 0.7); }
  70% { box-shadow: 0 0 0 10px rgba(255, 152, 0, 0); }
  100% { box-shadow: 0 0 0 0 rgba(255, 152, 0, 0); }
}

.promotion-info .promotion-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #ffffff;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.flash-icon {
  display: inline-block;
  margin-right: 5px;
  animation: flash-icon 1.5s infinite;
}

@keyframes flash-icon {
  0% { transform: scale(1); }
  50% { transform: scale(1.2); }
  100% { transform: scale(1); }
}

.promotion-info .promotion-rule {
  color: #ffffff;
  margin-bottom: 5px;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
  font-size: 18px;
  font-weight: bold;
}

.promotion-info .promotion-time {
  color: #ffffff;
  font-size: 12px;
  opacity: 0.9;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  display: none; /* 隐藏时间信息 */
}

.product-detail .product-price {
  font-size: 28px;
  margin-bottom: 10px;
}

.product-detail .product-stock {
  font-size: 16px;
  color: #666;
  margin-bottom: 10px;
}

.product-detail .product-description {
  font-size: 16px;
  color: #666;
  margin-bottom: 20px;
  line-height: 1.6;
}

.product-actions {
  display: flex;
  justify-content: center;
  margin-top: 30px;
  width: 100%;
}

.action-container {
  display: flex;
  align-items: center;
  gap: 10px;
}
</style>
